package com.bugbuff.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.bugbuff.dubbo.server.pojo.RecommendUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserLikeApi userLikeApi;

    @Override
    public RecommendUser queryByToUserId(Long id) {
//        System.out.println(mongoTemplate);
        //根据toUserId查询的数据，对score进行降序排序，获取第一个最高值
        Query query = Query.query(Criteria.where("toUserId").is(id)).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 查询登陆者推荐地用户
     *
     * @param id
     * @return
     */
    @Override
    public List<RecommendUser> queryList(Long id, Integer page, Integer size) {
//        带有分页查询的结果
        PageRequest request = PageRequest.of(page - 1, size, Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(Criteria.where("toUserId").is(id)).with(request);
        return mongoTemplate.find(query, RecommendUser.class);
    }


    @Override
    public Double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)
                .and("userId").is(userId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (null != recommendUser) {
            return recommendUser.getScore();
        }
        return null;
    }


    @Override
    public List<RecommendUser> queryCardList(Long userId, Integer count) {
        //设置分页以及排序，按照得分倒序排序
        PageRequest pageRequest = PageRequest.of(0, count, Sort.by(Sort.Order.desc("score")));

        //排除已喜欢或不喜欢的用户
        List<Long> userIds = new ArrayList<>();
        //查询喜欢列表
        userIds.addAll(this.userLikeApi.queryLikeList(userId));

        //查询不喜欢列表
        userIds.addAll(this.userLikeApi.queryNotLikeList(userId));

        //构造查询条件
        Criteria criteria = Criteria.where("toUserId").is(userId);
        if(CollUtil.isNotEmpty(userIds)){
            //加入到查询条件中，排除这些用户
            criteria.andOperator(Criteria.where("userId").nin(userIds));
        }

        Query query = Query.query(criteria).with(pageRequest);
        return mongoTemplate.find(query, RecommendUser.class);
    }
}
